package com.wbdgj.ui.word_compaign;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.BranchAdapter;
import com.wbdgj.adapter.CampaignYhqAdapter;
import com.wbdgj.adapter.WordCompaignAdapter;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.model.ResultUrlModel;
import com.wbdgj.ui.booking.ChoiceRoomDialogActivity;
import com.wbdgj.ui.branch.BranchDetailActivity;
import com.wbdgj.ui.home.CampaignDetailActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.uitool.ShareBoard;
import com.wbdgj.ui.uitool.ShareBoardlistener;
import com.wbdgj.ui.uitool.SnsPlatform;
import com.wbdgj.utils.ListViewForScrollView;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;
import com.wbdgj.views.MyGridView;
import com.wbdgj.views.RichTextView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.facebook.Facebook;
import cn.jiguang.share.facebook.messenger.FbMessenger;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.twitter.Twitter;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

public class WordCompaignActivity extends BaseActivity implements PtrHandler{
    private Context context = this;
    private String id, cloud_id;
    private String bid;

    @BindView(R.id.contentRichTextView)
    RichTextView richTextView;

    @BindView(R.id.image)
    ImageView image;

    @BindView(R.id.tv_topTitle)
    TextView tv_topTitle;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.mdName)
    TextView mdName;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.branchGridView)
    MyGridView branchGridView;
    private BranchAdapter branchAdapter;

    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;
    @BindView(R.id.srcollView)
    ScrollView srcollView;

    private CampaignYhqAdapter campaignYhqAdapter;
    @BindView(R.id.yhqList)
    ListViewForScrollView yhqList;

    @BindView(R.id.down)
    ImageView down;

    private List<LinkedTreeMap> linkedTreeMapsCd ;
    private boolean isXs = true;
    private String urlStr, titleTxt, contentTxt;
    private int mAction = Platform.ACTION_SHARE;
    private ShareBoard mShareBoard;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
//            if (progressDialog != null && progressDialog.isShowing()) {
//                progressDialog.dismiss();
//            }
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_word_campaign_detail;
    }

    @Override
    protected void initView() {
        srcollView.scrollTo(0,0);
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        pfl_root.disableWhenHorizontalMove(true);

        id = getIntent().getStringExtra("id");
        appbranchactivityinfo();

        findViewById(R.id.tv_rightTitle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startActivity(new Intent(context, BranchCouponActivity.class).putExtra("branch_id", bid));
            }
        });
        findViewById(R.id.down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isXs){
                    isXs = false;
                    branchGridView.setVisibility(View.VISIBLE);
                    down.setImageResource(R.mipmap.booking_up);
                }else{
                    isXs = true;
                    branchGridView.setVisibility(View.GONE);
                    down.setImageResource(R.mipmap.booking_down);
                }
            }
        });
        branchGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!branchAdapter.hasNoData){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    startActivity(new Intent(context, BranchDetailActivity.class).putExtra("id", decimalFormat.format(branchAdapter.getItem(i).get("branch_id"))).putExtra("DISTANCE", ""));
                }
            }
        });

        findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(context,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(WordCompaignActivity.this
                            , new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
                    ToastUtils.toastShort("请打开您设备上的照片,媒体内容和文件访问权限!");
                    return;
                }
                createshareurl();
            }
        });

        findViewById(R.id.login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BaseApplication.getInstance().setlinkedTreeMapList(linkedTreeMapsCd);
                launch(WordCompaignDialogActivity.class);
            }
        });

        findViewById(R.id.yjlq_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定一键领取吗？", 1);
                confirmDialog.show();
                confirmDialog.setCanceledOnTouchOutside(false);
                confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        confirmDialog.dismiss();
                        getcouponall();
                    }

                    @Override
                    public void doCancel() {
                        confirmDialog.dismiss();
                    }
                });
            }
        });
    }

    private void getcouponall() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().getcouponall(id,  BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    private void act_rule() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().act_rule(bid,  BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    linkedTreeMapsCd = new ArrayList<>();
                    linkedTreeMapsCd = (List<LinkedTreeMap>) linkedTreeMap.get("data");
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    private void createshareurl() {
        Call<ResultUrlModel> call = HttpAdapter.getSerives().createshareurl(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), cloud_id);
        call.enqueue(new OnResponseListener<ResultUrlModel>(context) {
            @Override
            protected void onSuccess(ResultUrlModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    urlStr = HttpAdapter.HEAD_URL + userModelBaseResultModel.getUrl();
                    mAction = Platform.ACTION_SHARE;
                    showBroadView();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }


    private void appbranchactivityinfo() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().appnbnactivityinfo(id);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    LinkedTreeMap dataLink = (LinkedTreeMap) linkedTreeMap.get("data");
                    LinkedTreeMap actLink = (LinkedTreeMap) dataLink.get("act");
                    ArrayList<LinkedTreeMap> couponLink = (ArrayList<LinkedTreeMap>) dataLink.get("coupon");
                    ArrayList<LinkedTreeMap> hc_ruleLink = (ArrayList<LinkedTreeMap>) dataLink.get("hc_rule");

                    Glide.with(context).load(actLink.get("image")+"").placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(image);
                    tv_topTitle.setText(actLink.get("title")+"");
                    title.setText(actLink.get("title")+"");
                    time.setText((actLink.get("beg_time")+"").substring(0,(actLink.get("beg_time")+"").length()-3)+" ~ "+ (actLink.get("end_time")+"").substring(0,(actLink.get("beg_time")+"").length()-3));
                    mdName.setText(actLink.get("branch_name")+"");
                    cloud_id = actLink.get("cloud_id")+"";
                    bid = decimalFormat.format(actLink.get("id"));
                    titleTxt = actLink.get("title")+"";
                    contentTxt = actLink.get("content")+"";
                    List<LinkedTreeMap> branch = (List<LinkedTreeMap>) actLink.get("able_branch_name");
                    branchAdapter = new BranchAdapter(context, branch);
                    branchGridView.setAdapter(branchAdapter);
                    richTextView.setRichText(actLink.get("content")+"");

                    if(couponLink.size() == 0){
                        findViewById(R.id.yjlq_btn).setVisibility(View.GONE);
                        findViewById(R.id.yhqLay).setVisibility(View.GONE);
                    }else{
                        findViewById(R.id.yhqLay).setVisibility(View.VISIBLE);
                        findViewById(R.id.yjlq_btn).setVisibility(View.VISIBLE);
                    }
                    if(hc_ruleLink.size() == 0){
                        findViewById(R.id.login_btn).setVisibility(View.GONE);
                    }else{
                        findViewById(R.id.login_btn).setVisibility(View.VISIBLE);
                    }

                    if (couponLink.size() == 0){
                        yhqList.setVisibility(View.GONE);
                    }else{
                        campaignYhqAdapter = new CampaignYhqAdapter(context, couponLink, id);
                        yhqList.setAdapter(campaignYhqAdapter);
                    }

                    act_rule();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    Intent intent = new Intent(context, LoginActivity.class);
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }


    private String statusTxt(String type){
        if (type.equals("0")){
            return "待开始";
        }else if (type.equals("1")) {
            return "进行中";
        }else if (type.equals("2")) {
            return "已结束";
        }else{
            return " ";
        }
    }


    private void showBroadView() {
        if (mShareBoard == null) {
            mShareBoard = new ShareBoard(this);
            List<String> platforms = JShareInterface.getPlatformList();
            if (platforms != null) {
                Iterator var2 = platforms.iterator();
                while (var2.hasNext()) {
                    String temp = (String) var2.next();
                    SnsPlatform snsPlatform = createSnsPlatform(temp);
                    mShareBoard.addPlatform(snsPlatform);
                }
            }
            mShareBoard.setShareboardclickCallback(mShareBoardlistener);
        }
        mShareBoard.show();
    }

    private ShareBoardlistener mShareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, String platform) {

            switch (mAction) {
                case Platform.ACTION_SHARE:
//                    progressDialog.show();
                    //这里以分享链接为例
                    ShareParams shareParams = new ShareParams();
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setTitle(titleTxt);
                    shareParams.setText("查看活动详情");
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setUrl(urlStr);
//                    shareParams.setUrl("http://www.ahxfk.com/");
                    shareParams.setImagePath(BaseApplication.ImagePath);
                    JShareInterface.share(platform, shareParams, mShareListener);
                    break;
                default:
                    break;
            }
        }
    };

    private PlatActionListener mShareListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            Log.e("zp", "error:" + errorCode + ",msg:" + error);
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + error.getMessage() + "---" + errorCode;
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    public static SnsPlatform createSnsPlatform(String platformName) {
        String mShowWord = platformName;
        String mIcon = "";
        String mGrayIcon = "";
        String mKeyword = platformName;
        if (Wechat.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wechat";
            mGrayIcon = "jiguang_socialize_wechat";
            mShowWord = "jiguang_socialize_text_weixin_key";
        } else if (WechatMoments.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxcircle";
            mGrayIcon = "jiguang_socialize_wxcircle";
            mShowWord = "jiguang_socialize_text_weixin_circle_key";

        } else if (WechatFavorite.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxfavorite";
            mGrayIcon = "jiguang_socialize_wxfavorite";
            mShowWord = "jiguang_socialize_text_weixin_favorite_key";

        } else if (SinaWeibo.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_key";
        } else if (SinaWeiboMessage.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_msg_key";
        } else if (QQ.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qq";
            mGrayIcon = "jiguang_socialize_qq";
            mShowWord = "jiguang_socialize_text_qq_key";

        } else if (QZone.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qzone";
            mGrayIcon = "jiguang_socialize_qzone";
            mShowWord = "jiguang_socialize_text_qq_zone_key";
        } else if (Facebook.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_facebook";
            mGrayIcon = "jiguang_socialize_facebook";
            mShowWord = "jiguang_socialize_text_facebook_key";
        } else if (FbMessenger.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_messenger";
            mGrayIcon = "jiguang_socialize_messenger";
            mShowWord = "jiguang_socialize_text_messenger_key";
        }else if (Twitter.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_twitter";
            mGrayIcon = "jiguang_socialize_twitter";
            mShowWord = "jiguang_socialize_text_twitter_key";
        }
        return ShareBoard.createSnsPlatform(mShowWord, mKeyword, mIcon, mGrayIcon, 0);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        appbranchactivityinfo();
        pfl_root.refreshComplete();
    }
}
